package com.czl.module_service.viewmodel

import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.AssetHandleBean
import com.czl.base.data.bean.tengyun.ListBean
import com.czl.base.data.bean.tengyun.PurchaseBean
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper

class AssetHandleMyApplyViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var currentPage = 1
    var pageSize = 10
    val uc = UiChangeEvent()
    var titleNameObs = ObservableField("")

    class UiChangeEvent {
        val loadCompleteEvent: SingleLiveEvent<ListBean<AssetHandleBean>> = SingleLiveEvent()
        val loadFinallyEvent: SingleLiveEvent<Unit?> = SingleLiveEvent()
    }
    val reSearch: BindingCommand<Void> = BindingCommand(BindingAction {
        currentPage = 1
        this.selectMyHandleApplicationList()
    })

    val onLoadMoreListener: BindingCommand<Void> = BindingCommand(BindingAction {
        this.selectMyHandleApplicationList()
    })
    val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction {
        currentPage = 1
        this.selectMyHandleApplicationList()
    })

    private fun selectMyHandleApplicationList(
        companyId: String? = model.getLoginCompanyId(),
        userId: String? = model.getLocalUserInfo()?.userId
    ) {
        model.mTengYunHttpDataSource.selectMyHandleApplicationList(
            GsonUtils.toJson(
                mapOf(
                    "pageNo" to currentPage,
                    "pageSize" to pageSize,
                    "userId" to userId,
                    "companyId" to companyId,
                    "titleName" to titleNameObs.get()
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .doFinally {
                uc.loadFinallyEvent.postValue(null)
            }
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<AssetHandleBean>>>() {
                override fun onResult(t: BaseBean<ListBean<AssetHandleBean>>) {
                    if (t.state == 0) {
                        currentPage++
                        uc.loadCompleteEvent.postValue(t.data)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }
}